<?php
namespace App\Http\Controllers\Business\Admin\Statistic;

use App\Models\Comment;
use App\Models\FirstClass;
use App\Models\Order;
use App\Models\Recharge;
use App\Models\SecondClass;
use App\Models\User;
use App\Models\City;
use App\Models\Shop;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;

class StatisticManagement
{
    //统计概况
    public static function survey($cityId) {
        //累计用户数
        $totalUserCount = self::getTotalUserCount($cityId);
        //累计上线商家数
        $totalShopCount = self::getShopCountByStatus($cityId, 1);
        //累计订单数
        $totalOrderCount = self::getTotalOrderCount($cityId);
        //累计订单金额
        $totalOrderAmount = self::getTotalOrderAmount($cityId);
        //累计评论数
        $totalCommentCount = self::getTotalCommentCount($cityId);
        //今天新增用户数
        $todayUserCount = self::getTodayUserCount($cityId);
        //昨天新增用户数
        $yesterdayUserCount = self::getYesterdayUserCount($cityId);
        //近7天新增用户数
        $sevenDayUserCount = self::getUserCountByDays($cityId, 7);
        //近30天新增用户数
        $thirtyDayUserCount = self::getUserCountByDays($cityId, 30);
        //今天订单数
        $todayOrderCount = self::getTodayOrderCount($cityId);
        //昨天订单数
        $yesterdayOrderCount = self::getYesterdayOrderCount($cityId);
        //近7天订单数
        $sevenDayOrderCount = self::getOrderCountByDays($cityId, 7);
        //近30天订单数
        $thirtyDayOrderCount = self::getOrderCountByDays($cityId, 30);
        $data = [
            'totalusercount' => $totalUserCount,
            'totalshopcount' => $totalShopCount,
            'totalordercount' => $totalOrderCount,
            'totalorderamount' => $totalOrderAmount,
            'totalcommentcount' => $totalCommentCount,
            'todayusercount' => $todayUserCount,
            'yesterdayusercount' => $yesterdayUserCount,
            'sevendayusercount' => $sevenDayUserCount,
            'thirtydayusercount' => $thirtyDayUserCount,
            'todayordercount' => $todayOrderCount,
            'yesterdayordercount' => $yesterdayOrderCount,
            'sevendayordercount' => $sevenDayOrderCount,
            'thirtydayordercount' => $thirtyDayOrderCount,
        ];
        return $data;
    }
    //累计用户数
    public static function getTotalUserCount($cityId) {
        if(!$cityId) {
            return 0;
        }
        if($cityId == 1) {
            $data = User::where('created_at', '>=', '2016-07-01')->count();
        } else {
            $cityName = City::where('id', $cityId)->pluck('name')->first();
            $data = User::where('registerarea', $cityName)->count();
        }
        return $data;
    }
    //通过商家状态，获取累计商家数
    public static function getShopCountByStatus($cityId, $status=1) {
        if(!$cityId) {
            return 0;
        }
        $data = Shop::where('cityid', $cityId)->where('status', $status)->count();
        return $data;
    }
    //累计订单数
    public static function getTotalOrderCount($cityId) {
        if(!$cityId) {
            return 0;
        }
        //TODO 方案还需要讨论
        $shopIds = self::getShopIdArrayByCityId($cityId);
        $data = Order::whereIn('shopid', $shopIds)->count();
        return $data;
    }
    //累计订单金额
    public static function getTotalOrderAmount($cityId) {
        if(!$cityId) {
            return 0;
        }
        //TODO 方案还需要讨论
        $shopIds = self::getShopIdArrayByCityId($cityId);
        $data = Order::whereIn('shopid', $shopIds)->sum('orderamount');
        return $data;
    }
    //累计评论数
    public static function getTotalCommentCount($cityId) {
        if(!$cityId) {
            return 0;
        }
        //TODO 方案还需要讨论
        $shopIds = self::getShopIdArrayByCityId($cityId);
        $data = Comment::whereIn('shopid', $shopIds)->count();
        return $data;
    }
    //今天新增用户数
    public static function getTodayUserCount($cityId) {
        if(!$cityId) {
            return 0;
        }
        $cityName = City::where('id', $cityId)->pluck('name')->first();
        $today = date('Y-m-d')." 00:00:00";
        if($cityId == 1) {
            //总部
            $data = User::where('created_at', '>=', $today)->count();
        } else {
            $data = User::where('registerarea', $cityName)->where('created_at', '>=', $today)->count();
        }
        return $data;
    }
    //昨天新增用户数
    public static function getYesterdayUserCount($cityId) {
        if(!$cityId) {
            return 0;
        }
        $cityName = City::where('id', $cityId)->pluck('name')->first();
        $yesterday = date('Y-m-d', strtotime('-1day'))." 00:00:00";
        $today = date('Y-m-d') . " 00:00:00";
        if($cityId == 1) {
            //总部
            $data = User::where('created_at', '>=', $yesterday)->where('created_at', '<=', $today)->count();
        } else {
            //分部
            $data = User::where('registerarea', $cityName)->where('created_at', '>=', $yesterday)->where('created_at', '<=', $today)->count();
        }
        return $data;
    }
    //根据天数获取新增用户数
    public static function getUserCountByDays($cityId, $day=7) {
        if(!$cityId || !$day) {
            return 0;
        }
        $cityName = City::where('id', $cityId)->pluck('name')->first();
        $dateTime = date('Y-m-d', strtotime('-'.$day.'days'))." 00:00:00";
        if($cityId == 1) {
            $data = User::where('created_at', '>=', $dateTime)->count();
        } else {
            $data = User::where('registerarea', $cityName)->where('created_at', '>=', $dateTime)->count();
        }
        return $data;
    }
    //今天新增订单数
    public static function getTodayOrderCount($cityId) {
        if(!$cityId) {
            return 0;
        }
        //TODO 方案还需要讨论
        $shopIds = self::getShopIdArrayByCityId($cityId);
        $today = date('Y-m-d') . " 00:00:00";
        $data = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $today)->count();
        return $data;
    }
    //昨天新增订单数
    public static function getYesterdayOrderCount($cityId) {
        if(!$cityId) {
            return 0;
        }
        //TODO 方案还需要讨论
        $shopIds = self::getShopIdArrayByCityId($cityId);
        $yesterday = date('Y-m-d', strtotime('-1day')) . " 00:00:00";
        $today = date('Y-m-d') . " 00:00:00";
        $data = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $yesterday)->where('created_at', '<', $today)->count();
        return $data;
    }
    //根据天数获取新增订单数
    public static function getOrderCountByDays($cityId, $day=7) {
        if(!$cityId) {
            return 0;
        }
        //TODO 方案还需要讨论
        $shopIds = self::getShopIdArrayByCityId($cityId);
        $dateTime = date('Y-m-d', strtotime('-'.$day.'days')) . " 00:00:00";
        $data = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $dateTime)->count();
        return $data;
    }
    //通过城市id，获取该城市下所有的商家id
    protected static function getShopIdArrayByCityId($cityId) {
        if(!$cityId) {
            return [];
        }
        $data = Shop::where('cityid', $cityId)->select('id')->get();
        return $data;
    }
    //折线图
    public static function getTimeAxis($cityId, $days=7) {
        if(!$cityId) {
            return [];
        }
        $timeAxis = [];
        for($i=$days; $i>0; $i--) {
            $myDate = date('m-d', strtotime('-'.($i-1).'days'));
            array_push($timeAxis, $myDate);
        }
        return $timeAxis;
    }
    //折线图（用户数）近7天／30天
    public static function getUserChartData($cityId, $days=7) {
        if(!$cityId) {
            return [];
        }
        $daysAgo = date('Y-m-d', strtotime('-'.$days.'days')) . " 00:00:00";
        $countAxis = [];
        if($cityId == 1) {
            //总部
            $users = User::where('created_at', '>=', $daysAgo)->select('created_at')->get();
        } else {
            $cityName = City::where('id', $cityId)->pluck('name')->first();
            $users = User::where('registerarea', $cityName)->where('created_at', '>=', $daysAgo)->select('created_at')->get();
        }
        $dateTime = strtotime(date('Y-m-d') . " 23:59:59");
        for($i=$days; $i>0; $i--) {
            $startTimestamp = $dateTime - 60 * 60 * 24 * $i ; //TODO 时区处理
            $endTimestamp = $dateTime - 60 * 60 * 24 * ($i-1);
            $count = 0;
            foreach ($users as $user) {
                $createdAt = $user->created_at;
                $createdAtTimestamp = strtotime($createdAt);
                if (($createdAtTimestamp >= $startTimestamp) && ($createdAtTimestamp < $endTimestamp)) {
                    $count++;
                }
            }
            array_push($countAxis, $count);
        }
        return $countAxis;
    }
    //折线图（订单数）
    public static function getOrderChartData($cityId, $days=7) {
        if(!$cityId) {
            return [];
        }
        $daysAgo = date('Y-m-d', strtotime('-'.$days.'days')) . " 00:00:00";
        $countAxis = [];
        if($cityId == 1) {
            //总部
            $orders = Order::where('created_at', '>=', $daysAgo)->select('created_at')->get();
        } else {
            //分部
            $shopIds = Shop::where('cityid', $cityId)->select('id')->get();
            $orders = Order::whereIn('shopid', $shopIds)->where('created_at', '>=', $daysAgo)->select('created_at')->get();
        }
        $dateTime = strtotime(date('Y-m-d') . " 23:59:59");
        for($i=$days; $i>0; $i--) {
            $startTimestamp = $dateTime - 60 * 60 * 24 * $i ; //TODO 时区处理
            $endTimestamp = $dateTime - 60 * 60 * 24 * ($i-1);
            $count = 0;
            foreach ($orders as $order) {
                $createdAt = $order->created_at;
                $createdAtTimestamp = strtotime($createdAt);
                if (($createdAtTimestamp >= $startTimestamp) && ($createdAtTimestamp < $endTimestamp)) {
                    $count++;
                }
            }
            array_push($countAxis, $count);
        }
        return $countAxis;
    }

    //通过品类去获取订单数据
    public static function orderListByClassId($cityId, $startTime, $lastTime) {
        if(!$cityId || !$startTime|| !$lastTime) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $firstClasses = FirstClass::where('status', 1)->select('id as firstclassid', 'name as firstclassname')->get();
        $data = [];
        foreach($firstClasses as $firstClass) {
            $secondClassCount = 0;
            $firstClassId = $firstClass['firstclassid'];
            $secondClasses = SecondClass::where('firstclassid', $firstClassId)->where('status', 1)->select('id as secondclassid', 'name as secondclassname')->get();
            $childLists = [];
            foreach($secondClasses as $secondClass) {
                ++$secondClassCount;
                $secondClassId = $secondClass['secondclassid'];
                $childClass = self::getOrderStatisticBySecondClassIdAndDateTime($cityId, $secondClassId, $startTime, $lastTime);
                $childClass['secondclassid'] = $secondClassId;
                $childClass['secondclassname'] = $secondClass['secondclassname'];
                array_push($childLists, $childClass);
            }
            array_push($data, [
                'firstclassid' => $firstClassId,
                'firstclassname' => $firstClass['firstclassname'],
                'secondclasscount' => $secondClassCount,
                'childlists' => $childLists
            ]);
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //通过二级分类和起始时间获取消费金额，实付金额，订单总数
    protected static function getOrderStatisticBySecondClassIdAndDateTime($cityId, $secondClassId, $startTime, $lastTime) {
        if(!$cityId||!$secondClassId||!$startTime||!$lastTime) {
            return [
                'orderamount' => 0,
                'actualamount' => 0,
                'ordernum' => 0
            ];
        }
        $orderAmount = 0;
        $actualAmount = 0;
        $orderNum = 0;
        $shopIds = self::getShopIdsWithOrderByDateTime($cityId, $startTime, $lastTime);
        foreach($shopIds as $shopId => $val) {
            if($val != $secondClassId) {
                continue;
            }
            $orderAmount += Order::where('shopid', $shopId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->sum('orderamount');
            $actualAmount += Order::where('shopid', $shopId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->sum('actualamount');
            $orderNum += Order::where('shopid', $shopId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->count();
        }
        return [
            'orderamount' => $orderAmount,
            'actualamount' => $actualAmount,
            'ordernum' => $orderAmount
        ];
    }
    //通过起始时间获取订单商家ids
    protected static function getShopIdsWithOrderByDateTime($cityId, $startTime, $lastTime) {
        $shopIds = Order::where('cityid', $cityId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->distinct('shopid')->get();
        $data = [];
        foreach($shopIds as $shopId) {
            $data['shopid'] = Shop::where('id', $shopId)->pluck('secondclassid')->first();
        }
        //Redis::set('Admin:Statistic:Order:ShopId'. Auth::guard('adminweb')->id(), $data, 86400);
        return $data;
    }
    //导出通过二级分类获取订单数据
    public static function exportOrderListByClassId() {

    }
    //通过商家获取订单数据
    public static function orderListByShop($cityId, $startTime, $lastTime,$perpage=50, $page=1, $search='')
    {
        if (empty($cityId) || !is_numeric($cityId)) {
            return ['status' => 'failed', 'message' => '城市定位错误'];
        };
        if ($search) {
            $GLOBALS['search'] = $search;
            $data = Shop::where('shops.cityid', $cityId)
                ->where(function ($query) {
                    $query->orwhere('shops.name', 'like', '%'.$GLOBALS['search'].'%');
                })
                ->join('admin_users', 'shops.maintainerid', '=', 'admin_users.id')
                ->select('shops.id as shopid', 'shops.code as shopcode', 'shops.name as shopname', 'shops.districtname', 'shops.businessareaname', 'admin_users.realname', 'shops.status')
                ->get();
            foreach ($data as $k => $v) {
                $data[$k]['sumorderamount'] = Order::where('shopid', $v['shopid'])->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->sum('orderamount');
                $data[$k]['sumactualamount'] = Order::where('shopid', $v['shopid'])->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->sum('actualamount');
                $data[$k]['ordercount'] = Order::where('shopid', $v['shopid'])->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->count();
            }
        } else {
            $skip = ($page-1)*$perpage;
            $data = Shop::where('shops.cityid', $cityId)
                ->join('orders', 'shops.id', '=', 'orders.shopid')
                ->where('orders.created_at', '>=', $startTime)->where('orders.created_at', '<=', $lastTime)
                ->join('admin_users', 'shops.maintainerid', '=', 'admin_users.id')
                ->select('shops.id as shopid', 'shops.code as shopcode', 'shops.name as shopname', 'shops.districtname', 'shops.businessareaname',
                    'admin_users.realname', 'shops.status', DB::raw('count(*) as ordercount, shopid'), DB::raw('sum(orderamount) as sumorderamount, shopid'),
                    DB::raw('sum(actualamount) as sumactualamount, shopid'))
                ->groupby('orders.shopid')
                ->orderBy('ordercount','desc')
                ->skip($skip)->take($perpage)->get();
        }
        return ['status'=>'success','data'=>$data];
    }
    //通过起始时间获取用订单数量
    public static function getOrderCountByFromDateAndToDate($cityId, $startTime, $lastTime) {
        if(!$startTime || !$lastTime) {
            $startTime = '2016-01-01 00:00:00';
            $lastTime = date('Y-m-d H:i:s',time());
        }
        if($cityId == 1) {
            //南昌总部
            $data = Order::where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->where('shopid','!=','0')->distinct('shopid')->count('shopid');
        } else {
            //分部
            $data = Order::where('cityid', $cityId)->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->count();
        }
        return $data;
    }
    //导出通过商家获取订单数据
    public static function exportOrderListByShop($cityId, $startTime, $lastTime,$search) {
        if (empty($cityId) || !is_numeric($cityId)) {
            return ['status' => 'failed', 'message' => '城市定位错误'];
        };
        if ($search) {
            $GLOBALS['search'] = $search;
            $data = Shop::where('shops.cityid', $cityId)
                ->where(function ($query) {
                    $query->orwhere('shops.code', $GLOBALS['search'])->orwhere('shops.name', 'like', '%'.$GLOBALS['search'].'%')
                        ->orwhere('shops.districtname', 'like', '%'.$GLOBALS['search'].'%');
                })
                ->join('admin_users', 'shops.maintainerid', '=', 'admin_users.id')
                ->select('shops.id as shopid', 'shops.code as shopcode', 'shops.name as shopname', 'shops.districtname', 'shops.businessareaname', 'admin_users.realname', 'shops.status')
                ->get();
            foreach ($data as $k => $v) {
                $data[$k]['sumorderamount'] = Order::where('shopid', $v['shopid'])->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->sum('orderamount');
                $data[$k]['sumactualamount'] = Order::where('shopid', $v['shopid'])->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->sum('actualamount');
                $data[$k]['ordercount'] = Order::where('shopid', $v['shopid'])->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->count();
            }
        } else {
            $data = Shop::where('shops.cityid', $cityId)
                ->join('orders', 'shops.id', '=', 'orders.shopid')
                ->where('orders.created_at', '>=', $startTime)->where('orders.created_at', '<=', $lastTime)
                ->join('admin_users', 'shops.maintainerid', '=', 'admin_users.id')
                ->select('shops.id as shopid', 'shops.code as shopcode', 'shops.name as shopname', 'shops.districtname', 'shops.businessareaname',
                    'admin_users.realname', 'shops.status', DB::raw('count(*) as ordercount, shopid'), DB::raw('sum(orderamount) as sumorderamount, shopid'),
                    DB::raw('sum(actualamount) as sumactualamount, shopid'))
                ->groupby('orders.shopid')
                ->get();
        }
        return ['status'=>'success', 'data'=>$data];
    }
}